package com.milo.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
* @description: Excel工具类
* @author: Milogenius
* @date: 2018/10/16 15:42 
**/

public class ExcelUtils {

    final Logger logger = LoggerFactory.getLogger(ExcelUtils.class);

    public Workbook getWorkbook(String path) {
        Workbook workbook;
        try {
            InputStream inputStream = new FileInputStream(path);
            workbook = WorkbookFactory.create(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return workbook;
    }

    public Sheet getSheet(Workbook workbook, int index) {
        Sheet Sheet;
        try {
            if (workbook != null) {
                Sheet = workbook.getSheetAt(index);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return Sheet;
    }



    /**
     * 从 Excel 获取数据(单个 Sheet)
     * @param excelFilePath
     * @param CellNames 每一列数据的 name, 此数据的每一项用来当返回数据的Key
     * @param readIndex 从 Excel 的哪一行开始读取数据, 从0开始
     * @return
     */
    public List<Map<String, String>> excel2List(String excelFilePath, String[] CellNames, int readIndex) {
        int LastCellNum = CellNames.length;
        Workbook workbook = getWorkbook(excelFilePath);
        Sheet sheet = getSheet(workbook, 0);//默认读取第一个 sheet
        if (sheet == null || workbook == null) {
            logger.info("===> sheet 或者 workbook 为空");
            return null;
        }
        List<Map<String, String>> data = new ArrayList<>();
        int lastRowNum = sheet.getLastRowNum();
        for (int i = readIndex; i <= lastRowNum; i++) {
            //读取每一行
            Row row = sheet.getRow(i);
            //处理空数据, 每一行的第一列如果为空, 则不读取
            if (StringUtils.isEmpty(row.getCell(0).toString())) {
                continue;
            }
            //读取每一行有多少列
            //short LastCellNum = row.getLastCellNum();
            Map<String, String> rowMap = new HashMap<>(LastCellNum + 1);
            for (int b = 0; b < LastCellNum; b++) {//读取每一行每一列的数据
                rowMap.put(CellNames[b], row.getCell(b).toString());
            }
            data.add(rowMap);
        }
        return data;
    }




    /**
     * 从 Excel 获取数据(多个 Sheet)
     * @param excelFilePath
     * @param CellNames 每一列数据的 name, 此数据的每一项用来当返回数据的Key
     * @param sheetAt Sheet 的索引
     * @param readIndex 从 Excel 的哪一行开始读取数据, 从0开始
     * @return
     */
    public List<Map<String, String>> excel2List(String excelFilePath, String[] CellNames, int sheetAt, int readIndex) {
        int LastCellNum = CellNames.length;
        Workbook workbook = getWorkbook(excelFilePath);
        Sheet sheet = getSheet(workbook, sheetAt);//默认获取第 sheetAt 个数据
        if (sheet == null || workbook == null) {
            logger.info("===> sheet 或者 workbook 为空");
            return null;
        }
        List<Map<String, String>> data = new ArrayList<>();
        int lastRowNum = sheet.getLastRowNum();
        for (int i = readIndex; i <= lastRowNum; i++) {
            //读取每一行
            Row row = sheet.getRow(i);
            Map<String, String> rowMap = new HashMap<>(LastCellNum + 2);
            for (int b = 0; b < LastCellNum; b++) {//读取每一行每一列的数据
                rowMap.put(CellNames[b], row.getCell(b).toString());
            }
            data.add(rowMap);
        }
        return data;
    }

    public Workbook list2Excel(String[] titles, String[] cellKeys, List<Map<String, String>> data) {
        int LastCellNum = cellKeys.length;
        int titlesNum = titles.length;
        if (LastCellNum != titlesNum) {
            logger.info("===> 列名的大小和列Key 大小不一致");
            return null;
        }
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        //创建标题
        Row title = sheet.createRow(0);
        for (int b = 0; b < LastCellNum; b++) {
            Cell cell = title.createCell(b);
            cell.setCellValue(titles[b]);
        }
        //填写数据, 从第二行开始
        for (int a = 0; a < data.size(); a++) {
            Map<String, String> rowData = data.get(a);
            Row row = sheet.createRow(a + 1);
            logger.info(rowData.toString());
            for (int b = 0; b < LastCellNum; b++) {
                String cellValue = rowData.get(cellKeys[b]);
                Cell cell = row.createCell(b);
                cell.setCellValue(cellValue);
                sheet.autoSizeColumn(b, true);
            }
        }
        return workbook;
    }


    /**
     * 导出数据到Excle
     * @param titles
     * @param cellKeys
     * @param data
     * @param ExcelFileName
     * @param response
     */

    public void list2Excel(
            String[] titles,
            String[] cellKeys,
            List<Map<String, String>> data,
            String ExcelFileName,
            HttpServletResponse response
    ) {
        OutputStream outputStream = null;
        try {
            Workbook workbook = list2Excel(titles, cellKeys, data);
            response.reset();
            response.addHeader("Content-Type", "applicationnd.ms-excel; charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(ExcelFileName + ".xlsx", "UTF-8"));
            response.addHeader("Pragma", "public");
            response.addHeader("Cache-Control", "max-age=0");
            outputStream = response.getOutputStream();
            if (workbook != null) {
                logger.info("===> workbook: " + workbook);
                workbook.write(outputStream);
            }
            
//            OutputStream out = response.getOutputStream();
//    		response.setContentType("application/x-msdownload");
//    		response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(ExcelFileName+ ".xlsx", "UTF-8"));
//    		workbook.write(out);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

public static void main(String[] args) {
        String[] CellNames = {"a", "b", "c"};
        String path = "D:\\workspace\\IDEA\\Test\\src\\com\\company\\test.xls";
        // List<Map<String, Object>> list1 = excel2List(path, CellNames, 0);
        //
        //
        String[] titles = {"列一", "列二", "列三"};
        String[] cellKeys = {"a", "b", "c"};
        List<Map<String, Object>> data = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("a", "张三");
        map.put("b", "男");
        map.put("c", "20");
        data.add(map);
        //
        map = new HashMap<>();
        map.put("a", "李四");
        map.put("b", "女女女女女女女女女女女女女");
        map.put("c", "22");
        data.add(map);
        map = new HashMap<>();
        map.put("a", "王五王五王五王五王五王五王五王");
        map.put("b", "");
        map.put("c", "42");
        data.add(map);
       // Workbook workbook = list2Excel(titles, cellKeys, data);
       Workbook workbook = null;
        try {
            FileOutputStream out = new FileOutputStream("D:\\workspace\\IDEA\\Test\\src\\com\\company\\测试.xlsx");
            workbook.write(out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
